#import "database.h"
#import "ReportCache.h"

#define MAX_CACHE_SIZE 256

#undef DEBUG

#if !defined(DEBUG)
#define NSLog(...) 
#endif

static NSMutableDictionary *cache = nil;

@implementation DeliveryReportCache 
+(void)init {
	if (cache == nil)
		cache =[ [NSMutableDictionary dictionaryWithCapacity:64] retain];
}

+(void)flush {
	[cache removeAllObjects];
}

+(void)flushIfNeeded {
	if ([cache count] > MAX_CACHE_SIZE)
		[DeliveryReportCache flush];
}

+(_Bool)reportForRowid:(uint32_t)rowid {
    _Bool res = NO;
    NSNumber *report = nil;
    int ref, delay, status;
    time_t date;
	NSNumber *key = [NSNumber numberWithInteger:rowid];

	NSLog(@"%s rowid=%d", __FUNCTION__, rowid);
    if (cache == nil) [DeliveryReportCache init];
    report = [cache objectForKey:key];

	if (report == nil) {
		int rc = get_delivery_info_for_rowid(rowid, &ref, &date, &delay, &status);
		if (rc == 0) {
            report = [NSNumber numberWithBool:(res = status == 0)];

			[DeliveryReportCache flushIfNeeded];

			[cache setObject:report forKey:key];
			[report release];
		}
	}
    else
        res = [report boolValue];

	NSLog(@"report = %d", res);
    return res;
}
@end

// vim: ft=objc ts=4 expandtab
